package com.macro.mall.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.service.RedisService;
import com.macro.mall.common.util.DateUtil;
import com.macro.mall.common.util.StringIf;
import com.macro.mall.dao.PmsStockDao;
import com.macro.mall.dao.UmsMemberDao;
import com.macro.mall.domain.AgentSkuListResult;
import com.macro.mall.dto.UmsCheckInDto;
import com.macro.mall.mapper.UmsMemberMapper;
import com.macro.mall.model.UmsMember;
import com.macro.mall.model.UmsMemberExample;
import com.macro.mall.model.UmsStore;
import com.macro.mall.service.UmsDistributionMemberService;
import com.macro.mall.service.UmsStoreService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * UmsAdminService实现类
 * Created by macro on 2018/4/26.
 */
@Transactional
@Service
public class UmsDistributionMemberServiceImpl implements UmsDistributionMemberService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UmsAdminServiceImpl.class);
    @Autowired
    private UmsMemberMapper umsMemberMapper;
    @Autowired
    private UmsMemberDao umsMemberDao;
    @Autowired
    private UmsStoreService umsStoreService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private RedisService redisService;
    @Autowired
    private PmsStockDao pmsStockDao;
    @Override
    @Transactional(readOnly = true)
    public List<UmsMember> list(Long userId,Integer pageNum,Integer pageSize,String realName,String phone,Integer type) {
        UmsMemberExample example = new UmsMemberExample();
        UmsMemberExample.Criteria criteria = example.createCriteria();
        criteria.andStoreUserIdEqualTo(userId);
        if(!StringUtils.isEmpty(phone)&&phone!=null){
            criteria.andPhoneEqualTo(phone);
        }
        if(!StringUtils.isEmpty(realName)&&realName!=null){
            criteria.andRealNameLike("%"+realName+"%");
        }
        criteria.andTypeEqualTo(type);
        PageHelper.startPage(pageNum, pageSize);
        example.setOrderByClause("create_time desc");
        List<UmsMember> umsMembers = this.umsMemberMapper.selectByExample(example);
        return umsMembers;
    }

    @Override
    public CommonResult addOrBindUser(String userName, UmsMember umsMember) {
        UmsStore store = this.umsStoreService.getStoreIdByUsername(userName);//获取当前门店店主相关信息
        umsMember.setStoreId(store.getId());
        umsMember.setStoreUserId(store.getUserId());
        umsMember.setType(1);
        //签到情况
        umsMember.setCheckIn(getNewCheckIn());
        //用表中无用的字段成长值来区别普通用户是普通用户，还是分销商解绑后成为的普通用户
        umsMember.setGrowth(1);
        Date date = new Date();
        umsMember.setCreateTime(date);
        int i = 0;
//        //根据手机号查询
//        UmsMemberExample example = new UmsMemberExample();
//        example.createCriteria().andPhoneEqualTo(umsMember.getPhone());
//        List<UmsMember> umsMemberList = this.umsMemberMapper.selectByExample(example);
//        //如果该手机号存在就修改
//
//        if(umsMemberList.size()>0&&umsMemberList.get(0).getPhone().equals(umsMember.getPhone()) && umsMemberList.get(0).getType().equals(0)
//                    && umsMemberList.get(0).getGrowth() == null){
//            //该手机号已存在普通用户
//            return CommonResult.failed("该手机号已绑定普通用户");
//        }else if(umsMemberList.size()>0&&umsMemberList.get(0).getPhone().equals(umsMember.getPhone())){
//            umsMember.setId(umsMemberList.get(0).getId());
//            umsMember.setAgentId(umsMemberList.get(0).getId());
//            umsMember.setPassword(null);
//            i = this.umsMemberMapper.updateByPrimaryKeySelective(umsMember);
//        }else{//新增用户，并绑定门店，做乡村经纪人
//            //判断用户名是否重复
//            UmsMemberExample userExample = new UmsMemberExample();
//            userExample.createCriteria().andUsernameEqualTo(umsMember.getUsername());
//            List<UmsMember> umsMembers = umsMemberMapper.selectByExample(userExample);
//            if(!CollectionUtils.isEmpty(umsMembers)){
//                return CommonResult.failed("用户名重复，请重新输入");
//            }
//            //通过查redis中有没有获取验证码的记录，来验证注册的手机号是不是刚才发验证码的
//            String key = "code:" + umsMember.getPhone();
//            Object o = redisService.get(key);
//            if(null == o){
//                return CommonResult.failed("请输入获取验证码的手机号");
//            }
//            umsMember.setUuid(StringIf.getUUId());
//            umsMember.setStatus(1);//是否禁用：1不禁用
//            //将密码进行加密操作
//            String encodePassword = passwordEncoder.encode(umsMember.getPassword());
//            umsMember.setPassword(encodePassword);
//            i = this.umsMemberMapper.insertSelective(umsMember);
//        }
        //根据手机号查询
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andPhoneEqualTo(umsMember.getPhone());
        List<UmsMember> umsMemberList = this.umsMemberMapper.selectByExample(example);
        //如果该手机号存在就修改
        if(umsMemberList.size()>0&&umsMemberList.get(0).getPhone().equals(umsMember.getPhone())){
            umsMember.setId(umsMemberList.get(0).getId());
            umsMember.setAgentId(umsMemberList.get(0).getId());
            umsMember.setPassword(null);
            i = this.umsMemberMapper.updateByPrimaryKeySelective(umsMember);
        }else{//新增用户，并绑定门店，做乡村经纪人
            //判断用户名是否重复
            UmsMemberExample userExample = new UmsMemberExample();
            userExample.createCriteria().andUsernameEqualTo(umsMember.getUsername());
            List<UmsMember> umsMembers = umsMemberMapper.selectByExample(userExample);
            if(!CollectionUtils.isEmpty(umsMembers)){
                return CommonResult.failed("用户名重复，请重新输入");
            }
            umsMember.setUuid(StringIf.getUUId());
            umsMember.setStatus(1);//是否禁用：1不禁用
            //将密码进行加密操作
            String encodePassword = passwordEncoder.encode(umsMember.getPassword());
            umsMember.setPassword(encodePassword);
            i = this.umsMemberMapper.insertSelective(umsMember);
            umsMember.setAgentId(umsMember.getId());
            umsMember.setPassword(null);
            this.umsMemberMapper.updateByPrimaryKeySelective(umsMember);
        }
        if (i > 0) {
            return CommonResult.success("");
        }else {
            return CommonResult.failed("保存乡村经纪人失败，请稍后再试");
        }
    }

    @Override
    @Transactional(readOnly = true)
    public CommonPage<UmsMember> queryMembersByDistributionId(Long distributionId, Integer pageSize, Integer page){
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andAgentIdEqualTo(distributionId).andIdNotEqualTo(distributionId);
        PageHelper.startPage(page,pageSize);
        List<UmsMember> umsMembers = this.umsMemberMapper.selectByExample(example);
        return CommonPage.restPage(umsMembers);
    }

    @Override
    public List<UmsMember> queryMembersByDistributionId(Long distributionId) {
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andAgentIdEqualTo(distributionId).andIdNotEqualTo(distributionId);
        return this.umsMemberMapper.selectByExample(example);
    }

    @Override
    @Transactional(readOnly = true)
    public long getMemberCountByDistributionId(Long distributionId){
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andAgentIdEqualTo(distributionId).andIdNotEqualTo(distributionId);
        return this.umsMemberMapper.countByExample(example);
    }

    @Override
    public CommonResult<CommonPage<UmsMember>> getMemberByAgent(Long agentId, String phone, Integer pageNum, Integer pageSize) {
        //获取分销商信息
        UmsMember agent = umsMemberMapper.selectByPrimaryKey(agentId);
        UmsMemberExample example = new UmsMemberExample();
        UmsMemberExample.Criteria criteria = example.createCriteria();
        criteria.andAgentIdEqualTo(agentId).andStoreIdEqualTo(agent.getStoreId()).andIdNotEqualTo(agentId);
        if(phone != null && !"".equals(phone.trim())){
            criteria.andPhoneLike("%" + phone + "%");
        }
        //改分销商下的所有用户
        PageHelper.startPage(pageNum, pageSize);
        List<UmsMember> umsMembers = umsMemberMapper.selectByExample(example);
        CommonPage<UmsMember> umsMemberCommonPage = CommonPage.restPage(umsMembers);
        return CommonResult.success(umsMemberCommonPage);
    }

    @Override
    public CommonResult transferMember(String ids, Long newAgentId) {
        // 把字符串拼接的id转成List<Long>
        List<Long> memberIds = StringIf.getList4Long(ids);
        if (newAgentId.equals(memberIds.get(0))) {
            return CommonResult.failed("相同用户不能转移");
        }
        //修改用户的分销商
        UmsMember record = new UmsMember();
        record.setAgentId(newAgentId);
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andIdIn(memberIds);
        int count = umsMemberMapper.updateByExampleSelective(record, example);
        if (count > 0) {
            return CommonResult.success(count);
        }else {
            return CommonResult.failed();
        }
    }

    /**
     * 获取经纪人库存列表
     *
     * @param agentId  经纪人id
     * @param pageNum
     * @param pageSize
     * @return
     * @author 孙晓亮
     * @date 2020年9月21日
     */
    @Override
    public List<AgentSkuListResult> getAgentSkuList(Long agentId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<AgentSkuListResult> agentSkuListResults = pmsStockDao.getAgentSkuList(agentId);
        return agentSkuListResults;
    }



    /**
     * 新用户checkIn字段为空，根据当前周几重置
     *
     * @return
     */
    private String getNewCheckIn() {
        UmsCheckInDto dto;
        int week = DateUtil.getWeek();
        switch (week) {
            case 1:
                dto = new UmsCheckInDto(0, 2, 2, 2, 2, 2, 2);
                break;
            case 2:
                dto = new UmsCheckInDto(2, 0, 2, 2, 2, 2, 2);
                break;
            case 3:
                dto = new UmsCheckInDto(2, 2, 0, 2, 2, 2, 2);
                break;
            case 4:
                dto = new UmsCheckInDto(2, 2, 2, 0, 2, 2, 2);
                break;
            case 5:
                dto = new UmsCheckInDto(2, 2, 2, 2, 0, 2, 2);
                break;
            case 6:
                dto = new UmsCheckInDto(2, 2, 2, 2, 2, 0, 2);
                break;
            case 7:
                dto = new UmsCheckInDto(2, 2, 2, 2, 2, 2, 0);
                break;
            default:
                dto = new UmsCheckInDto();
        }
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(dto);
        String checkIn = jsonObject.toString();
        return checkIn;
    }
}
